package nzb;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.beanutils.converters.NumberConverter;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import play.Logger;

public class NzbHandler extends DefaultHandler{
	
	private List<NzbFile>	files;
	private List<String>	tmpGroups;
	private List<Segment>	tmpSegments;
	
	private NzbFile 		tmpFile;
	private Segment			tmpSegment;
	private String			tmpGroup;
	private String 			contentString;
	
	 @Override
         public void characters(char[] ch, int start, int lenght) throws SAXException {
                 contentString += new String(ch, start, lenght);
         }
	
	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
	    	contentString = "";
		if(qName.equals("file")) {
			tmpFile = new NzbFile(attributes.getValue("poster"), new Date(Long.valueOf(attributes.getValue("date"))), attributes.getValue("subject"));
		} else if (qName.equals("groups")) {
			tmpGroups = new ArrayList<String>();
		} else if (qName.equals("segments")) {
			tmpSegments = new ArrayList<Segment>();
		} else if (qName.equals("group")) {
			tmpGroup = new String();
		} else if (qName.equals("segment")) {
			tmpSegment = new Segment(Long.valueOf(attributes.getValue("bytes")), (Number) Long.valueOf(attributes.getValue("number")));
		} else if (qName.equals("nzb")){
		} else {
			throw new SAXException("Balise : " + qName + " non géré.");
		}
	}
	
	
	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		
		if(qName.equals("file")) {
			tmpFile.setFileName(tmpFile.getSubject().split("\"")[1]);
			files.add(tmpFile);
			this.tmpFile = null;
		} else if (qName.equals("groups")) {
			tmpFile.setGroups(tmpGroups);
			this.tmpGroups = null;
		} else if (qName.equals("segments")) {
			tmpFile.setSegments(tmpSegments);
			this.tmpSegments = null;
		} else if (qName.equals("group")) {
		    	tmpGroup = contentString;
			tmpGroups.add(tmpGroup);
			this.tmpGroup = null;
		} else if (qName.equals("segment")) {
		    	this.tmpSegment.setId(contentString);
			tmpSegments.add(tmpSegment);
			this.tmpSegment = null;
		} else if (qName.equals("nzb")){
		} else {
			throw new SAXException("Balise : " + qName + " non géré.");
		}
	}
	
	//début du parsing
	public void startDocument() throws SAXException {
		this.files = new ArrayList<NzbFile>();
		System.out.println("Début du parsing");
	}
	//fin du parsing
	public void endDocument() throws SAXException {
		System.out.println("Fin du parsing");
		System.out.println("Resultats du parsing");
		for(NzbFile file : files){
			System.out.println(file);
		}
	}
	
	public List<NzbFile> getFiles()
	{
		return this.files;
	}
}
